package com.wss.common.utils;

import com.wss.common.base.BaseApplication;
import ohos.agp.components.Component;
import ohos.agp.components.ScrollView;
import ohos.agp.utils.Point;
import ohos.agp.utils.Rect;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.util.Optional;

public class KeyboardUtils {

    public void adjustPan(ScrollView scrollView) {
        Optional<Display> display = DisplayManager.getInstance().getDefaultDisplay(BaseApplication.i().getContext());
        Point pt = new Point();
        display.get().getSize(pt);
        int screenHeight = pt.getPointYToInt();//不包括状态栏(手机时间、wifi显示的那一部分，) 2211，状态栏是129，加起来就是2340

//        ScrollView root = (ScrollView) findComponentById(ResourceTable.Id_multiple_item_scroll);
        scrollView.setLayoutRefreshedListener(new Component.LayoutRefreshedListener() {
            @Override
            public void onRefreshed(Component component) {
                //包括标题栏，但不包括状态栏。默认 大小 (0,129,1080,2340),top=129即状态栏 , height=2211。
                Rect decorRect = new Rect();
                component.getWindowVisibleRect(decorRect);

                if (decorRect.getHeight() == 0) {
                    //刚进入界面可能为0
                    return;
                }
                int softHeight = screenHeight - decorRect.getHeight();

                if (softHeight > 100) {//当输入法高度大于100判定为输入法打开了
                    if (myTask != null) {
                        mainHandler.removeTask(myTask);
                        myTask = null;
                    }
                    mainHandler.postTask(myTask = new MyTask(softHeight, scrollView, decorRect), 100);
                }
            }
        });
    }

    private EventHandler mainHandler = new EventHandler(EventRunner.getMainEventRunner());
    private MyTask myTask = null;
    class MyTask implements Runnable {
        private final int softHeight;
        private final ScrollView root;
        private final Rect decorRect;

        public MyTask(int softHeight, ScrollView root, Rect decorRect) {
            this.softHeight = softHeight;
            this.root = root;
            this.decorRect = decorRect;
        }

        @Override
        public void run() {

            Component focusView = root.findFocus();
            if (focusView != null) {
                int focusTop = focusView.getLocationOnScreen()[1];//焦点控件的左上角
                root.fluentScrollByY(focusTop + focusView.getHeight() - decorRect.top - decorRect.getHeight() + 100);
            }
        }
    }
}
